<script setup>
import {Delete, Plus} from "@element-plus/icons-vue";
import {httpUpload} from "@/api";
import {computed} from "vue";
import {ElMessage} from "element-plus";

const props = defineProps({
  image: {
    type: String,
    default: ''
  },
  size: {
    type: Number,
    default: 1
  }
})
const emits = defineEmits(['update:image'])
const imageList = computed(() => {
  return (props.image || '').split(',').filter(empty => empty !== '')
})
const uploadAvatar = (file) => {
  const list = (props.image || '').split(',').filter(empty => empty !== '')
  if (list.length >= props.size) {
    return ElMessage.warning(`最多上传${props.size}张图片`)
  }
  // 上传头像
  httpUpload(file.file).then(res => {
    console.log(list)
    list.push(res.data.url)
    console.log(list)
    console.log(list.join(','))
    emits('update:image',list.join(','))
  })
}
const deleteImage = (item) => {
  const list = (props.image || '').split(',').filter(empty => empty !== '').filter(image => image !== item)
  emits('update:image',list.join(','))
}
</script>

<template>
  <div style="display: flex;" class="upload-image">
    <div v-for="item in imageList" :key="item" class="img-view">
      <div class="img-view-wrapper">
        <el-icon size="28px" @click="deleteImage(item)"><Delete></Delete></el-icon>
      </div>
      <el-image :src="item" class="avatar" style="margin-right: 10px"/>
    </div>
    <el-upload
        v-show="imageList.length < size"
        class="avatar-uploader"
        action="#"
        :http-request="uploadAvatar"
        :show-file-list="false"
        accept="image/*"
    >
      <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<style lang="scss">
.upload-image {
  display: flex;
  .gap {
    width: 32px;
  }
  .img-view {
    width: 120px;
    height: 120px;
    position: relative;
    margin-right: 16px;
    &:hover {
      .img-view-wrapper {
        display: inline-block;
      }
    }
    .img-view-wrapper {
      display: none;
      cursor: pointer;
      width: 100%;
      height: 100%;
      z-index: 2;
      position: absolute;
      left: 0;
      top: 0;
      background-color: rgba(0,0,0,0.8);
      line-height: 120px;
      text-align: center;
      > * {
        color: #ffffff;
      }
    }
  }
  .avatar {
    width: 120px;
    height: 120px;
  }
  .avatar-uploader {
    width: 120px;
  }
  .avatar-uploader .avatar {
    width: 100%;
    height: 120px;
    display: block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  .el-upload {
    width: 100%;
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 120px;
    text-align: center;
  }
}
</style>